var ws;
var timer;
var wsstate;

sid = "";
wsstate = "";

function startWS()
{
	var url = curl+":9998";
	ws = new WebSocket(url.replace('http:','ws:').replace('https:','wss:'));

	ws.onopen = function(e)
	{
		$('#wsstate').text('[opened]');
		wsstate = "opened";
		timer = setInterval(function(){keepalive()},60000);	

		var notify = {};
		notify.jsonrpc = "2.0";
		notify.method = "Login";
		var params = {};
		params.user = usr;
		params.sid = sid;
		notify.params = params;

		var str = JSON.stringify(notify);
		ws.send(str);			
		$('#ws').text("");
		$('#ws').append(str);
	}

	ws.onclose = function(e)
	{
		$('#ws').text('[closed]');
		wsstate = "closed";
		clearInterval(timer);
	}

	ws.onmessage = function(e)
	{
		if ( $('#ws').text().length > 1024 )
		{
			$('#ws').text('');
		}
		var time = getSysCurTime();
		$('#ws').append("\n");
		$('#ws').append(time);
		$('#ws').append(e.data);
		$('#ws').append("\n");

		var scrollTop = $('#ws')[0].scrollHeight;  
					$('#ws').scrollTop(scrollTop);
	}

	ws.onerror = function(e)
	{
		$('#wsstate').text('[websocket error]');
	}
}

function stopWS()
{
	var notify = {};
	notify.jsonrpc = "2.0";
	notify.method = "Logout";
	var params = {};
	params.user = usr;
	params.sid = sid;
	notify.params = params;

	var str = JSON.stringify(notify);
	ws.send(str);			
	$('#ws').text("");
	$('#ws').append(str);	
}

function keepalive()
{
	if(wsstate=="opened")
	{
		var notify = {};
		notify.jsonrpc = "2.0";
		notify.method = "NotifySID";
		var params = {};
		params.sid = sid;
		notify.params = params;
		var str = JSON.stringify(notify);
		ws.send(str);
		$('#ws').text("");
		$('#ws').append(str);
	}               
}       
